package com.aiti.lulian.controller.promotion;

import com.aiti.base.core.base.controller.WebController;
import com.aiti.base.core.constant.MessageCodeConstant;
import com.aiti.base.core.utils.message.Message;
import com.aiti.lulian.dto.CardPromotionDto;
import com.aiti.lulian.entity.crad.promotion.CardPromotion;
import com.aiti.lulian.entity.crad.promotion.CardPromotionSub;
import com.aiti.lulian.feign.CloudShowManagerSubService;
import com.aiti.lulian.service.ICardPromotionService;
import com.aiti.lulian.service.ICardPromotionSubService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.LinkedHashMap;
import java.util.Map;

@RestController
@Api(tags = "名片推广控制层")
@RequestMapping("/card/promotion")
public class CardPromotionController extends WebController {

    private final ICardPromotionService baseService;

    private final ICardPromotionSubService subService;

    private final CloudShowManagerSubService cloudShowManagerSubService;

    public CardPromotionController(ICardPromotionService baseService,ICardPromotionSubService subService,CloudShowManagerSubService cloudShowManagerSubService) {
        this.baseService = baseService;
        this.subService = subService;
        this.cloudShowManagerSubService = cloudShowManagerSubService;
    }

    /**
     * 推广人的转发次数的增加
     * @param params promotionCode - 推广码
     * @return 结果
     */
    @PostMapping("/updatePromotionForwardingCount")
    public Message updatePromotionForwardingCount(@RequestBody Map<String,String> params){
        String promotionCode = params.get("promotionCode");
        if(StringUtils.isBlank(promotionCode)){
            return Message.fail("promotionCode not found");
        }
        //首先查找关联人的表中的数据，如果没有找到那扫码的就可能扫的推广人的二维码
        CardPromotionSub subPromotionInfo = subService.getOne(new QueryWrapper<CardPromotionSub>().eq("promotion_code", promotionCode).isNull("delete_time"));
        //表示这个推广码存在关联账户中
        if(subPromotionInfo != null){
            subService.update(new UpdateWrapper<CardPromotionSub>().setSql("forwarding_count = forwarding_count + 1").eq("promotion_code", promotionCode).isNull("delete_time"));
            //推广人的数据也需要加计数累加
            //推广人的Id
            String pkId = subPromotionInfo.getPkId();
            baseService.update(new UpdateWrapper<CardPromotion>().setSql("forwarding_count = forwarding_count + 1").eq("base_id",pkId).isNull("delete_time"));
        }else{
            //如果走到这个分支这个推广码是在推广人的表中
            CardPromotion masterPromotion = baseService.getOne(new QueryWrapper<CardPromotion>().eq("promotion_code", promotionCode).isNull("delete_time"));
            if(masterPromotion != null){
                baseService.update(new UpdateWrapper<CardPromotion>().setSql("forwarding_count = forwarding_count + 1").eq("promotion_code", promotionCode).isNull("delete_time"));
            }else{
                //走到这里有可能是关联人删除,所以这里要查询出已删除的关联人
                CardPromotionSub deleteSub = subService.getOne(new QueryWrapper<CardPromotionSub>().eq("promotion_code", promotionCode));
                if(deleteSub != null){
                    String masterId = deleteSub.getPkId();
                    baseService.update(new UpdateWrapper<CardPromotion>().setSql("forwarding_count = forwarding_count + 1").eq("base_id",masterId).isNull("delete_time"));
                }
            }
        }
        return Message.success();
    }

    @PostMapping("/updatePromotionRegisterCount")
    public Message updatePromotionRegisterCount(@RequestBody Map<String,String> params){
        String promotionCode = params.get("promotionCode");
        if(StringUtils.isBlank(promotionCode)){
            return Message.fail("promotionCode not found");
        }
        String userName = params.get("userName");
        if(StringUtils.isBlank(userName)){
            return Message.fail("userName not found");
        }
        Message userIdByUserName = cloudShowManagerSubService.getUserIdByUserName(userName);
        if(userIdByUserName.getCode().equals(MessageCodeConstant.MSG_FAIL_CODE)){
            return Message.fail("userName info get fail");
        }
        LinkedHashMap r = (LinkedHashMap)userIdByUserName.getObj();
        String userId = (String)r.get("userId");
        //如果用户Id存在，则不是新注册的用户
        if(StringUtils.isNotBlank(userId)){
            return Message.success();
        }
        //首先查找关联人的表中的数据，如果没有找到那扫码的就可能扫的推广人的二维码
        CardPromotionSub subPromotionInfo = subService.getOne(new QueryWrapper<CardPromotionSub>().eq("promotion_code", promotionCode).isNull("delete_time"));
        if(subPromotionInfo != null){
            subService.update(new UpdateWrapper<CardPromotionSub>().setSql("register_count = register_count + 1").eq("promotion_code", promotionCode).isNull("delete_time"));

            //推广人的数据也需要加计数累加
            //推广人的Id
            String pkId = subPromotionInfo.getPkId();
            baseService.update(new UpdateWrapper<CardPromotion>().setSql("register_count = register_count + 1").eq("base_id",pkId).isNull("delete_time"));
        }else{
            //如果走到这个分支这个推广码是在推广人的表中
            CardPromotion masterPromotion = baseService.getOne(new QueryWrapper<CardPromotion>().eq("promotion_code", promotionCode).isNull("delete_time"));
            if(masterPromotion != null){
                baseService.update(new UpdateWrapper<CardPromotion>().setSql("register_count = register_count + 1").eq("promotion_code", promotionCode).isNull("delete_time"));
            }else{
                //走到这里有可能是关联人删除
                CardPromotionSub deleteSub = subService.getOne(new QueryWrapper<CardPromotionSub>().eq("promotion_code", promotionCode));
                if(deleteSub != null){
                    String masterId = deleteSub.getPkId();
                    baseService.update(new UpdateWrapper<CardPromotion>().setSql("register_count = register_count + 1").eq("base_id",masterId).isNull("delete_time"));
                }
            }
        }
        return Message.success();
    }

    @GetMapping("/page")
    public Message page(CardPromotionDto dto) {
        Page page = startPage(dto);
        return baseService.promotionList(page, dto);
    }

    @DeleteMapping("/delete")
    public Message delete(@RequestParam("baseId") String baseId) {
        return baseService.deletePromotion(baseId);
    }

    /**
     * 设置比例
     * @param dto
     * @return
     */
    @PutMapping("/setRatio")
    public Message setRatio(@RequestBody CardPromotionDto dto) {
        return baseService.setRatio(dto);
    }

    @ApiOperation("新增推广人")
    @PostMapping("/addPromoter")
    public Message addPromoter(@RequestBody CardPromotionDto cardPromotionDto){
//        cardPromotionDto.setBaseCreateBy("6576c4dd-47df-40d4-8013-17c86fda8ed0");
        cardPromotionDto.setBaseCreateBy(findUserId());
        return baseService.addPromoter(cardPromotionDto);
    }

    @ApiOperation("查询推广人数据")
    @GetMapping("/getPromoter")
    public Message getPromoterByBaseId(@RequestParam("baseId") String baseId){
        return Success(baseService.getPromoterByBaseId(baseId));
    }

    @ApiOperation("编辑关联账号")
    @PutMapping("/updatePromoter")
    public Message updatePromoter(@RequestBody CardPromotionDto cardPromotionDto){
//        cardPromotionDto.setBaseCreateBy("6576c4dd-47df-40d4-8013-17c86fda8ed0");
        cardPromotionDto.setBaseCreateBy(findUserId());
        return baseService.updatePromoter(cardPromotionDto);
    }

    /**
     * 可删：true，不可删：false
     */
    @ApiOperation("判断当前关联账号是否为可删除的")
    @GetMapping("/isDeletable")
    public Message queryIsDeletable(@RequestParam("baseId") String baseId){
        return baseService.queryIsDeletable(baseId);
    }

    @ApiOperation("查询当前企业下已记录的推广人或关联账号")
    @GetMapping("/queryPromoterByEnterpriseId")
    public Message queryPromoterByEnterpriseId(@RequestParam("enterpriseId") String enterpriseId){
        return baseService.queryPromoterByEnterpriseId(enterpriseId);
    }

    @ApiOperation("查询当前企业下已记录的推广人或关联账号（排除指定用户）")
    @GetMapping("/queryPromoterByEnterpriseIdExcludeSelection")
    public Message queryPromoterByEnterpriseIdExcludeSelection(@RequestParam("enterpriseId") String enterpriseId, @RequestParam("userId") String userId){
        return baseService.queryPromoterByEnterpriseIdExcludeSelection(enterpriseId, userId);
    }
    @ApiOperation("提现")
    @PutMapping("/withdraw")
    public Message withdraw(@RequestBody CardPromotionDto dto) {
        dto.setBaseCreateBy(findUserId());
        return baseService.withdraw(dto);
    }

    /**
     * 通过用户Id获取该用户的推广码
     * @param userId 用户Id
     * @return 推广码 - 可能为空
     */
    @GetMapping("/selectPromoterCodeByUserId")
    public Message selectPromoterCodeByUserId(@RequestParam("userId") String userId){
        CardPromotion cardPromotion = baseService.getOne(new QueryWrapper<CardPromotion>().eq("user_id", userId).isNull("delete_time"));
        String promotionCode = "";
        if(cardPromotion != null){
            promotionCode = cardPromotion.getPromotionCode();
        }else{
            CardPromotionSub cardPromotionSub = subService.getOne(new QueryWrapper<CardPromotionSub>().eq("user_id", userId).isNull("delete_time"));
            if(cardPromotionSub != null){
                promotionCode = cardPromotionSub.getPromotionCode();
            }
        }
        return Message.success(promotionCode);
    }
}